package com.ace.log.file

import android.util.Log
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.io.IOException


class FileWriter(private var folderPath: String) {

    var lastFileName: String? = null
        private set

    var file: File? = null
        private set

    private var bufferedWriter: BufferedWriter? = null

    val isOpened: Boolean
        get() = bufferedWriter != null

    fun open(newFileName: String): Boolean {
        file = File(folderPath, newFileName)
        lastFileName = file?.name
        file?.let {
            if (!it.exists()) {
                try {
                    val parent = it.parentFile
                    if (!parent.exists()) {
                        parent.mkdirs()
                    }
                    it.createNewFile()
                } catch (e: IOException) {
                    e.printStackTrace()
                    lastFileName = null
                    file = null
                    return false
                }
            }
            try {
                bufferedWriter = BufferedWriter(FileWriter(it, true))
            } catch (e: Exception) {
                e.printStackTrace()
                lastFileName = null
                file = null
                return false
            }
            return true
        }

        return false
    }

    fun close(): Boolean {
        bufferedWriter?.let {
            try {
                it.close()
            } catch (e: IOException) {
                e.printStackTrace()
                return false
            } finally {
                lastFileName = null
                file = null
            }
        }
        return true
    }

    fun appendLog(log: String) {
        bufferedWriter?.let {
            try {
                it.write(log)
                it.flush()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}